﻿// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>MyCompany.MyProject</Solution>
// <Project>MyCompany.MyProject.Core</Project>
// <FileName>SearchRecordDomainService.cs</FileName>
// <CreateTime>2017-04-22 21:55</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-04-22 21:55" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Vecen.BangChuang.BangChuang.Common;

namespace Vecen.BangChuang.BangChuang.DomainServices.Common {
    public class SearchRecordDomainService: BangChuangDomainServiceBase, ITransientDependency {
        private readonly IRepository<SearchRecord> _searchRecordRepository;

        public SearchRecordDomainService(IRepository<SearchRecord> searchRecordRepository) {
            _searchRecordRepository = searchRecordRepository;
        }

        /// <summary>
        /// 创建搜索记录
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task CreateSearchRecordAsync(string keyword) {
            var record =
                await _searchRecordRepository.FirstOrDefaultAsync(
                    c => c.CreatorUserId == AbpSession.UserId && c.KeyWord == keyword);

            if(record != null) {
                record.LastSearchTime = DateTime.Now;
                record.SearchCount++;
            } else {
                record = new SearchRecord();
                record.KeyWord = keyword;
                record.LastSearchTime = DateTime.Now;
                record.SearchCount++;
            }

            await _searchRecordRepository.InsertOrUpdateAndGetIdAsync(record);
        }
    }
}